const config = require('../config')
const jwt = require('jsonwebtoken')
const mongoose = require('mongoose')
const joi = require('joi')
joi.objectId = require('joi-objectid')(joi)

//定义用户数据库user结构
const adminSchema = new mongoose.Schema({
    //用户名
    username: {
        type: String,
        required: true,
        minlength:  6,
        maxlength: 20,
        unique: true
    },
    password: {
        type: String,
        required: true,
        minlength: 6,
        maxlength: 1000,
        select: false
    },
    //隐藏版本信息__v
    __v: {
        type: Number,
        select: false
    },
    //权限
    role:{
        type:String,
        select:false,
        default:1
    },
    //头像
    avatar: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Avatar',
        default: "6352d1f81d500d4c690b102a"
    },

})


//封装生成token的功能
adminSchema.methods.generateToken = function () {
    return jwt.sign({
        _id: this._id
    }, config.secret, { expiresIn: '7day' })
}
//引入用户模块
const Admin = mongoose.model("Admin", adminSchema)

function adminValidator(data) {
    const schema = joi.object({
        username: joi.string().min(6).max(20).messages({
            "any.required": "缺少必选的参数nickname",
            "string.base": "nickname必须为String类型",
            "string.min": "nickname最少为2字符",
            "string.max": "nickname最多为14字符"
        }),
        password: joi.string().pattern(/^[a-zA-Z0-9!@.?]{6,16}$/).messages({
            "string.base": "password必须为String类型",
            "string.min": "password最少为6字符",
            "string.max": "password最多为16字符",
            "string.pattern.base": "密码格式错误,包含大小写英文数字和!@.?"
        }),
        _id: joi.objectId,
        avatar: joi.objectId().messages({
            "string.base": '图片地址必须为string类型'
        }),
        role: joi.string().default(1)
     
    })
    return schema.validate(data)
}

module.exports = {
    Admin,
    adminValidator
}